package info.nene_loveplus.controller.admin;

import info.nene_loveplus.Attr;
import info.nene_loveplus.meta.blog.EntryMeta;
import info.nene_loveplus.model.AudioFile;
import info.nene_loveplus.model.blog.Entry;
import info.nene_loveplus.service.BlogService;

import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.util.StringUtil;

import com.google.appengine.api.datastore.Text;

public class CreateController extends AbstractAdminController {

	private static EntryMeta E = EntryMeta.get();

	private BlogService blogService = new BlogService();

	@Override
	public Navigation doRun() {
		Validators v = new Validators(request);
		v.add(E.title, v.required(), v.maxlength(100));
		v.add(E.content, v.required());
		if (!v.validate()) {
			return forward("dashboard.jsp");
		}

		Entry e = new Entry();
		if (!StringUtil.isEmpty(param("key"))) {
			e.setKey(asKey("key"));
		}
		e.setTitle(asString(E.title));
		e.setContent(new Text(asString(E.content)));

		if (!StringUtil.isEmpty(param("audioFileUrl"))) {
			AudioFile a = new AudioFile();
			a.setUrl(asString("audioFileUrl"));

			e.getAudioFileRef().setModel(a);
		}

		blogService.createEntry(e);

		requestScope(Attr.MESSAGE, "投稿しました。");

		return forward("list");
	}
}
